#include <iostream>
#include <map>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#include "normaliser.hpp"
#include <string>
#include <client/dbclient.h>
unsigned int BUF_SIZE=1024;
char *command_str="ls *.so";
map<string,maker_t *> factory;
map<string,maker_t *>::iterator fitr;
list<void *> dl_list;
list<void *>::iterator itr;
list<string> norm_list;
list<string>::iterator nitr;
void open_libs()
{
    char in_buf[BUF_SIZE];
    FILE *dl=popen(command_str,"r");
    if(!dl)
    {
        perror("popen");
        exit(-1);
    }
    void *dlib;
    char name[1024],i;
    while(fgets(in_buf,BUF_SIZE,dl))
    {
        char *ws=strpbrk(in_buf," \t\n");
        if(ws) *ws='\0';
        sprintf(name,"./%s",in_buf);
        dlib=dlopen(name,RTLD_NOW);
        if(dlib==NULL)
        {
            cerr<<dlerror()<<endl;
            exit(-1);
        }
        dl_list.insert(dl_list.end(),dlib);
    }
}
void load_identifiers()
{
    int i=0;
    for(fitr=factory.begin();fitr!=factory.end();fitr++)
    {
        norm_list.insert(norm_list.end(),fitr->first);
        i++;
    }
}
string get_idmatch(string input)
{
    list<string>::iterator nitrl;
    size_t found;
    string rs="";
    for(nitrl=norm_list.begin();nitrl!=norm_list.end();nitrl++)
    {
        found=input.find(*nitrl);
        if(found!=string::npos)
        {
            rs=*nitrl;
            return rs;
        }
    }
    return rs;
}
    


int main()
{
    //void *dlib;
    //dlib=dlopen("./snort.so",RTLD_NOW);
    //normaliser *obj=factory["snort"]();
    string input="Jan  8 14:27:55 ubuntuDev snort[12617]: [1:1590:7] WEB-CGI faqmanager.cgi arbitrary file access attempt [Classification: Web Application Attack] [Priority: 1]: {TCP} 192.168.23.1:31011 -> 192.168.23.135:80";
    open_libs();
    load_identifiers();
    string id=get_idmatch(input);
    if(id=="")
    {return -1;}
    normaliser *obj=factory[id]();
    mongo::BSONObj b=obj->normalise(input);
    cout<<b.toString()<<endl;
    return 0;
}
